import Vue from "vue";
import Vuex from "vuex";
import authApi from "../server/auth";
import cartApi from "../server/cart";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    username: "",
    userInfo: {
      username: "",
      created_time: ""
    },
    cart_num: 0,
    token: "",
    isLogin: false
  },
  mutations: {
    setLogin(state, name) {
      state.username = name;
      state.isLogin = true;
    },
    clearLogin(state) {
      state.username = "";
      state.isLogin = false;
    },
    setUserInfo(state, { username, created_time }) {
      state.userInfo = {
        username,
        created_time
      };
    },
    setCartNum(state, num) {
      state.cart_num = num;
    }
  },
  actions: {
    getUserInfo({ commit }) {
      authApi.getDetail().then(data => {
        commit("setLogin", data);
      });
    },
    updateCartNum({ commit }) {
      cartApi.get().then(data => {
        commit("setCartNum", data.length || 0);
      });
    }
  },
  modules: {}
});
